package com.agentlab.imitation.web.action;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Controller;

import com.agentlab.imitation.bean.DimZxdm;
import com.agentlab.imitation.bean.PageView;
import com.agentlab.imitation.bean.User;
import com.agentlab.imitation.common.CommonConstant;
import com.agentlab.imitation.service.DimZxdmService;
import com.agentlab.imitation.service.UserService;
import com.agentlab.imitation.util.DateTimeUtils;
import com.agentlab.imitation.util.MD5;
import com.opensymphony.xwork2.ActionSupport;


@Controller 
public class UserManagerAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@Resource UserService usersService;
	@Resource DimZxdmService dimZxdmService;
	private User user;
	
	private String message; // ajax result

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	@SuppressWarnings("unchecked")
	private HashMap dqzxMap;
	@SuppressWarnings("unchecked")
	public HashMap getDqzxMap() {
		return dqzxMap;
	}


	@SuppressWarnings("unchecked")
	public void setDqzxMap(HashMap dqzxMap) {
		this.dqzxMap = dqzxMap;
	}
	
	/**
	 * 用户管理列表显示
	 */
	public String listUI(){
		HttpServletRequest req = ServletActionContext.getRequest();
		//最大页 10，当前页 1
		int iPage = 1;
		if(req.getParameter("page") != null){
			String spage = req.getParameter("page").toString();
			iPage = (Integer.parseInt(spage))<1 ?1 : Integer.parseInt(spage);
		}
		PageView<User> pageView = new PageView<User>(10, iPage);
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("createtime", "desc");

		StringBuffer jpql = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		pageView.setQueryResult(
				usersService.getScrollData(pageView.getFirstResult(), pageView.getMaxresult()
						, jpql.toString(), params.toArray(), orderby)
		);
		req.setAttribute("pageView", pageView);
		return "userlist";
	}
	
//	/**
//	 * 启用
//	 * @throws IOException 
//	 */
//	public String enable() throws IOException{
//		HttpServletRequest req = ServletActionContext.getRequest();
//		String[] useremail = null;
//		useremail = (String[]) req.getParameterMap().get("useremails");
//		usersService.enable((Serializable[])useremail);
//		req.setAttribute("message", "启用成功");
//		return "listaction";
//	}
	/**
	 * 禁用
	 * @throws IOException 
	 */
	public String delete() throws IOException{
		HttpServletRequest req = ServletActionContext.getRequest();
		String[] useremail = null;
		useremail = (String[]) req.getParameterMap().get("useremails");
		usersService.delete((Serializable[])useremail);
		req.setAttribute("message", "禁用成功");
		return "listaction";
	}
	
	/**
	 * 检查用户名是否存在
	 */
	public String checkUserByName() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String username = request.getParameter("user.username");
		if (usersService.getUserByName(username) != null) {
			this.setMessage("存在");
		} else {
			this.setMessage("不存在");
		}
		return "message";
	}
	
	/**
	 * 检查邮箱是否已经注册过
	 */
	public String checkUserByEmail() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String email = request.getParameter("user.email");
		if (usersService.getUserByEmail(email) != null) {
			this.setMessage("存在");
		} else {
			this.setMessage("不存在");
		}
		return "message";
	}
	
	/**
	 * 增加或修改
	 */
	public String addorupdate(){
		HttpServletRequest req = ServletActionContext.getRequest();
		try {
			User orgusers = getUser();
			if(orgusers == null){
				orgusers = new User();
			}
			orgusers.setUsername(user.getUsername());
			orgusers.setEmail(user.getEmail());
			String newpass = req.getParameter("newuserpass");
//			String[] rols = null;
//			rols = (String[])  req.getParameterMap().get("userrolecode");
			
			if(StringUtils.isNotBlank(newpass)){
				orgusers.setPassword(MD5.MD5Encode(newpass));
			}else{
				orgusers.setPassword(MD5.MD5Encode(user.getPassword()));
			}
			orgusers.setStatus(Short.parseShort("1"));
			if(user.getUserid() != null){
				if(newpass.length()==0){
					orgusers.setPassword(user.getPassword());
				}
				usersService.update(user);
			}else{
				orgusers.setCreateTimestamp(DateTimeUtils.getDateTimeStamp());
				usersService.save(user);
			}
			
			
			req.getSession().setAttribute("addupdateresultmsg", "增加用户成功！用户名：" + orgusers.getUsername());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "listaction";
	}
	
	public String main(){
		HttpServletRequest req = ServletActionContext.getRequest();
		User user = (User)req.getSession().getAttribute(CommonConstant.USER_SESSION);
		if(user == null){
			return "usernopermission";
		}else{
			this.setUser(user);
			return "main";
		}
	}
	
	/**
	 * 进入编辑
	 * @throws IOException 
	 */
	
	public String editUI() throws IOException{
		HttpServletRequest req = ServletActionContext.getRequest();
		User user = (User)req.getSession().getAttribute(CommonConstant.USER_SESSION);
		if(user == null){
			return CommonConstant.USER_NO_PERMISSION;
		}else{
			this.setUser(user);
			return "editui";
		}
	}
	/**
	 *编辑用户， 执行
	 * @throws IOException 
	 */
	public String edit() throws IOException{
		HttpServletRequest req = ServletActionContext.getRequest();
		User user = this.getUser();
		
		usersService.update(user);
		req.setAttribute("edit_result", "修改资料成功！");
		return "edit_result";
		
	}
	
	/**
	 * 进入详细资料编辑
	 * @throws IOException 
	 */
	
	public String detailUI() throws IOException{
		HttpServletRequest req = ServletActionContext.getRequest();
		User user = (User)req.getSession().getAttribute(CommonConstant.USER_SESSION);
		if(user == null){
			return CommonConstant.USER_NO_PERMISSION;
		}else{
			this.setUser(user);
			this.setDqzxMap(dimZxdmService.getMap());
			return "detailUI";
		}
	}
	/**
	 *详细资料编辑， 执行
	 * @throws IOException 
	 */
	public String editDetail() throws IOException{
		HttpServletRequest req = ServletActionContext.getRequest();
		User user = this.getUser();
		/*String xb = req.getParameter("user.xb");
		String csny = req.getParameter("user.csny");
		String kldm = req.getParameter("user.kldm");*/
		
		DimZxdm zx = dimZxdmService.getZxByZxmc(user.getZxmc());
		user.setSzdqdm(zx.getDqdm());
		user.setSzdqmc(zx.getDqmc());
		user.setZxdm(zx.getZxdm());
		user.setZxlbdm(zx.getZxlbdm());
		user.setZxlbmc(zx.getZxlbmc());
		
		//计算年龄
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
		String strYear = formatter.format(user.getCsny());
		int csyear = Integer.parseInt(strYear);
		int nowYear = Integer.parseInt( DateTimeUtils.getYear());
		int nl = (csyear <= nowYear) ? nowYear - csyear : 0 ;
		user.setNl(Short.parseShort(new Integer(nl).toString()));
		
		user.setUpdateTimestamp(DateTimeUtils.getDateTimeStamp());
		
		if(user.getKldm() != null){
			user.setKlmc((user.getKldm().equals("11") ? "文史类" : "理工类" ));
		}
		
		
		usersService.update(user);
		req.setAttribute("edit_result", "修改资料成功！");
		return "editDetail_result";
		
	}
	
	/**
	 * 进入用户修改密码界面
	 */
//	@Permission(module="sysuser", privilege="psupdate")
	public String  updatePassUI(){
		return "updatepass_ui";
	}
	
	/**
	 *修改密码， 执行
	 * @throws IOException 
	 */
	public String updatepass(){
		HttpServletRequest req = ServletActionContext.getRequest();
		User user = this.getUser();
		
		if(user == null){
			return CommonConstant.USER_NO_PERMISSION;
		}else{
			String newuserpass = req.getParameter("newuserpass");
			//取得新密码
			if(newuserpass == null || newuserpass.equals("")){ 
				req.setAttribute("message", "修改失败！新密码不能为空");
				return "updatepass_ui" ;
			}
			//判断原密码是否输入正确
			String olduserpass = req.getParameter("olduserpass");
			if(!MD5.MD5Encode(olduserpass).equals(user.getPassword())){
				req.setAttribute("message", "修改失败！当前密码错误");
				return "updatepass_ui" ;
			}
			
			user.setPassword(MD5.MD5Encode(newuserpass));
//			user.setUpdatetime(DateTimeUtils.getDateTimeStamp());
			usersService.update(user);
			req.getSession().setAttribute(CommonConstant.USER_SESSION, user);//将更新后的user写回session
			req.setAttribute("message", "修改成功");
			return "updatepass_result" ;
		}
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}
